package controller.book;

import dao.DaoException;
import dao.book.BookDaoImp;
import dao.borrow.BorrowDaoImpl;
import model.Borrow;
import model.Reader;
import utilities.Utilities;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

@WebServlet(name = "UpdateBookBorrowServlet", urlPatterns = "/updateBookBorrow")
public class UpdateBookBorrowServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session;
        BookDaoImp bookDao = new BookDaoImp();
        int bid = Integer.parseInt(request.getParameter("id"));
        int rid;

        session = request.getSession();
        Reader reader = (Reader) session.getAttribute("reader");
        rid = reader.getId();

        String state = request.getParameter("state");
        if ("borrow".equals(state)) {
            try {
                bookDao.updateBorrowBook(bid, "已借");
            } catch (DaoException e) {
                e.printStackTrace();
            }
            Date d = new Date();

            BorrowDaoImpl borrowDao = new BorrowDaoImpl();
            Borrow borrow = new Borrow(rid, bid, d, Utilities.stepMonth(d, 2));

            try {
                borrowDao.borrowBook(borrow);
            } catch (DaoException e) {
                e.printStackTrace();
            }

            response.sendRedirect("borrowBooks.jsp");
        } else if ("return".equals(state)) {
            try {
                bookDao.updateBorrowBook(bid, "未借");
            } catch (DaoException e) {
                e.printStackTrace();
            }

            BorrowDaoImpl borrowDao = new BorrowDaoImpl();
            try {
                borrowDao.returnBook(rid, bid);
            } catch (DaoException e) {
                e.printStackTrace();
            }
            response.sendRedirect("borrowBooksDetail.jsp");
        }
    }
}
